
import { Injectable } from '@nestjs/common';
import { DbService } from 'apps/admin/src/db/db.service';
import CreateDto from './dto/create.dto';
import UpdateDto from './dto/update.dto';
import { DictionaryCategory } from '@app/db/common/entity/DictionaryCategory';
import { DictionaryItem } from '@app/db/common/entity/DictionaryItem';

@Injectable()
export class DictionaryCategoryService {
    constructor(
        private readonly db:DbService
    ){}

    async items() {
        const res:{categorys:Array<DictionaryCategory>, items:Array<DictionaryItem>} = {
            categorys : [],
            items : []
        }

        res.categorys = await this.db.dictionaryCategory.find()
        res.items = await this.db.dictionaryItem.find()

        return res
    }

    async add(dto:CreateDto) {
        if((await this.db.dictionaryCategory.isExistsByWhere({name : dto.name}))) throw new Error('已存在相同的名称')
        if((await this.db.dictionaryCategory.isExistsByWhere({code : dto.code}))) throw new Error('已存在相同的编码')
        
        return this.db.dictionaryCategory.insert(dto)
    }

    async update(dto:UpdateDto) {
        const category = await this.db.dictionaryCategory.findOne({id : dto.id})
        if(!category) return false
        let updateData:{[key in keyof DictionaryCategory]? : DictionaryCategory[key]} = {}
        if(category.name != dto.name) {
            updateData.name = dto.name
        }

        if(category.code.toLocaleLowerCase() != dto.code.toLocaleLowerCase()) {
            updateData.code = dto.code
        }

        if((Object.keys(updateData)).length == 0) return true

        if(updateData.name && (await this.db.dictionaryCategory.isExistsByWhere({name : dto.name}))) throw new Error('已存在相同的名称')
        if(updateData.code && (await this.db.dictionaryCategory.isExistsByWhere({code : dto.code}))) throw new Error('已存在相同的编码')

        return this.db.dictionaryCategory.update({id : dto.id}, dto)
    }

    async del(id:number) {
        if((await this.db.dictionaryItem.isExistsByWhere({categoryId : id}))) throw new Error('该分类存在子分类，不可删除')
        return this.db.dictionaryCategory.delete({id : id})
    }
}
